package com.chengdu.chun.aopproxy;

import com.chengdu.chun.po.Classes;
import com.chengdu.chun.po.Loginfo;
import com.chengdu.chun.po.Student;
import com.chengdu.chun.po.User;
import com.chengdu.chun.service.LoginfoService;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class LogRecord {

    @Autowired
    private LoginfoService loginfoService;

    @Autowired
    private HttpSession session;

    /**
     * 监测单个班级信息的添加操作，并书写日志记录
     */
    @After("execution(* com.chengdu.chun.service.ClassesService.insertClasses(..))")
    public void addClasses(JoinPoint point) {
        User user = (User) session.getAttribute("user");
        // JoinPoint对象，可以获取到当前切点相关的数据对象和参数
        System.out.println("目标对象： " + point.getTarget());
        Classes classes = null;
        for (int i = 0; i < point.getArgs().length; i++) {
            if(point.getArgs()[i] instanceof Classes){
                classes = (Classes) point.getArgs()[i];
                break;
            }
        }
//        System.out.println("新的班级的名称: " + classes.getCname());
        Loginfo loginfo = new Loginfo();
        loginfo.setUid(user.getUid());
        Date date = new Date();
        String info = user.getUname()+"在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(date)
                +"  添加了新的班级："+classes.getCname();
        loginfo.setInfo(info);
        loginfo.setLtime(date);
        loginfo.setLdesc("添加新班级的操作");

        loginfoService.insert(loginfo);
        // 将信息作为调试debug信息格式输出到命令行，方便测试查看，正式上线后可以删除
        Logger.getRootLogger().debug(info);
    }

    @After("execution(* com.chengdu.chun.service.StudentService.insertStudent(..))")
    public void addStudent(JoinPoint point) {
        User user = (User) session.getAttribute("user");

        Student student = null;
        for (int i = 0; i < point.getArgs().length; i++) {
            if(point.getArgs()[i] instanceof Student){
                student = (Student) point.getArgs()[i];
                break;
            }
        }

        Loginfo loginfo = new Loginfo();
        loginfo.setUid(user.getUid());
        Date date = new Date();
        String info = user.getUname()+"  在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(date)
                +"  添加了新的学生："+student.getSname();
        loginfo.setInfo(info);
        loginfo.setLtime(date);
        loginfo.setLdesc("添加新学生的操作");
        loginfoService.insert(loginfo);
    }


}
